#!/usr/bin/env python
import numpy as np
import healpy as hp
from matplotlib import pyplot as plt

plt.ioff()

def showHpx(filename, ibin, alg='LIN', ExtIdx=1):
    h_map = hp.read_map(filename, field=ibin, hdu=ExtIdx, nest=False)
    alg = alg.lower()
    if alg == 'log':
        h_map= np.log10(np.abs(h_map))
        ma = np.isfinite(h_map)
        h_map[~ma] = h_map[ma].min() * 0.5
    elif alg == 'asinh':
        h_map = np.arcsinh(h_map)
    elif alg == 'sinh':
        h_map = np.sinh(h_map)
    elif alg == 'sqrt':
        h_map = np.sqrt(np.abs(h_map))*np.sign(h_map)
    elif alg == 'square':
        h_map = h_map**2*np.sign(h_map)
    elif alg == 'exp':
        h_map = np.exp(h_map)
    else:
        alg = 'lin'

    hp.mollview(h_map, coord='G', title="File:%s, bin:%s, extension: %s [%s]" % (filename, ibin+1, ExtIdx, alg))
    plt.show()

def cli():
    import argparse

    parser = argparse.ArgumentParser(description='Healpix Viewer')
    parser.add_argument("fileName", type=str, help='Healpix File Name')
    parser.add_argument("ibin", type=int, help='The index of the bin')
    parser.add_argument("alg", type=str, nargs='?', default='LIN', help='The algorithm, LIN|LOG|SINH|ASINH|SQRT|SQUARE|EXP')
    parser.add_argument("extIdx", type=int, nargs='?', default=1, help='The index of Extension')
    args = parser.parse_args()

    showHpx(args.fileName, args.ibin, args.alg, args.extIdx)


if __name__ == '__main__': cli()
